<template>
  <!--
    	作者：offline
    	时间：2018-09-10
    	描述：会计对账审批
  -->
  <div class="m-view-accountCheckInfo m-window" id="accAuditApp2">
    <div class="m-agTable m-bottom">
      <!-- <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="accountGridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        v-loading="loading"
        rowSelection="multiple"
      ></ag-grid-vue>-->
      <ag-grid-component
        ref="agGridComponent"
        :getColumnDefs="columnDefs"
        :getRowSelection="'multiple'"
        :tableName="'accountAuditList'"
        :getGridOptions="accountGridOptions"
        :getRowData="rowData"
        :isColFit="true"
        :systemInfo="$systemInfo"
        v-loading="loading"
      ></ag-grid-component>
    </div>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import constant from "@/public/constant";
import Msg from "@/public/message.js";
import gridOptions from "lesso-common/public/gridOptions";

export default {
  data() {
    return {
      columnDefs: [],
      rowData: [],
      loading: false,
      headerName: "",
    };
  },
  created() {
    if (this.$global.user.userTypeId == "4") this.headerName = "客户";
    else this.headerName = "公司";
  },
  beforeMount() {
    var colors = ["#FFFF00"];
    this.accountGridOptions = Object.assign(
      {
        context: {
          componentParent: this,
        },
        enableColResize: true,
        localeText: localeText,
        enableFilter: true, //列过滤器
        enableSorting: true, //列排序
        animateRows: true, //排序动画
        //suppressRowClickSelection: true, //jjc
        getRowStyle: function(params) {
          if (params.data.retFlag == "1" && params.data.billState == "1") {
            return {
              backgroundColor: colors[0],
            };
          } else {
            return {
              backgroundColor: null,
            };
          }
        },
        //   getContextMenuItems: this.getContextMenuItems
      },
      gridOptions({
        dragSelectCheckbox: true,
        singleSelection: true,
        operation: true,
      })
    );
    this.columnDefs = [
      {
        headerName: "会计对账单号",
        field: "accountNo",
        width: 180,
        cellRenderer: singleClickEditRenderer,
        checkboxSelection: true,
      },
      {
        headerName: this.headerName,
        field: "companyName",
        width: 180,
        tooltipField: "companyName",
      },
      {
        headerName: "供应商",
        field: "supplierName",
        width: 250,
        tooltipField: "supplierName",
      },
      { headerName: "期初", field: "sapOpenBalance", width: 120, hide: true },
      { headerName: "应付", field: "sapDebitSum", width: 120, hide: true },
      { headerName: "已付", field: "sapLendSum", width: 120, hide: true },
      {
        headerName: "余额",
        field: "sapBalance",
        width: 120,
        cellRenderer: function(params) {
          if (params.value)
            return params.value
              .toString()
              .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
          else return params.value;
        },
        hide: true,
      },
      { headerName: "合同编号", field: "contractNo", width: 160, hide: true },
      { headerName: "发票金额", field: "invoiceMoneySum", width: 120 },
      {
        headerName: "不符描述",
        field: "unConMemo",
        width: 150,
        tooltipField: "unConMemo",
      },
      {
        headerName: "审批意见",
        field: "operateMemo",
        width: 150,
        tooltipField: "operateMemo",
      },
      {
        headerName: "申请人",
        field: "creator",
        width: 100,
        tooltipField: "creator",
      },
      {
        headerName: "申请日期",
        field: "createDate",
        width: 100,
        cellRenderer: function(params) {
          if (params.value) {
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
          }
        },
      },
      { headerName: "确认人", field: "confirmer", width: 100 },
      {
        headerName: "确认日期",
        field: "confirmDate",
        width: 100,
        cellRenderer: function(params) {
          if (params.value) {
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
          }
        },
      },
      { headerName: "审批人", field: "auditor", width: 100 },
      {
        headerName: "审批日期",
        field: "auditDate",
        width: 100,
        cellRenderer: function(params) {
          if (params.value) {
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
          }
        },
      },
      {
        headerName: "单据状态",
        field: "billState",
        width: 100,
        cellRenderer: function(params) {
          if (params.value == "1") return '<span class="ag-icon">保存</span>';
          else if (params.value == "2")
            return '<span class="ag-icon">提交</span>';
          else if (params.value == "3")
            return '<span class="ag-icon">已确认</span>';
          else if (params.value == "4")
            return '<span class="ag-icon">已审核</span>';
        },
      },
    ];
  },
  methods: {
    getContextMenuItems() {
      return [];
    },
    // 设置表格列
    setColumnDefs() {
      this.$refs["agGridComponent"].gridOptions.api.setColumnDefs(
        this.columnDefs
      );
    },
    getDataRows(msg) {
      this.$refs.agGridComponent.gridOptions.api.setRowData(msg);
      // let allColumnIds = [];
      // this.accountGridOptions.columnApi.getAllColumns().forEach(function(column) {
      // 	allColumnIds.push(column.colId);
      // });
      //this.accountGridOptions.columnApi.autoSizeColumns(allColumnIds);
    },
    getSelectedRow() {
      var row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要删除的数据");
        return;
      }
      var that = this;
      this.$confirm("是否确认删除该数据？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true,
      })
        .then(() => {
          var id = "";
          for (var i = 0; i < row.length; i++) {
            id += row[i].id + ",";
          }
          id = id.substr(0, id.length - 1);
          var obj = {
            id: id,
            modifyer: this.$global.user.loginName,
            modifyerId: this.$global.user.id,
            state: 1,
          };
          _Api
            .deleteMyAccountList(obj)
            .then(function(response) {
              var data = response.data;
              if (data.code == "1") {
                Msg.showSuccessMsg("已审核");
                that.$refs.agGridComponent.gridOptions.api.updateRowData({
                  remove: row,
                });
              } else {
                Msg.showErrorMsg(data.info);
              }
            })
            .catch((err) => {
              Msg.showErrorMsg(err.data.message);
            });
        })
        .catch(() => {});
    },
    setClickValue(value) {
      this.$emit("getClickValue", value);
    },
    //审批会计对账单
    auditSelectedRows() {
      var that = this;
      var row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要审核的数据！");
        return;
      }

      this.$confirm("是否审核该数据？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true,
      }).then(function(response) {
        //批量审批会计对账单
        //上传签署文件
        for (let i = 0; i < row.length; i++) {
          var obj4 = {};
          obj4.supplierName = row[i].supplierName; //供应商
          obj4.companyName = row[i].companyName; //公司
          obj4.abortDate = row[i].createDate.substr(0, 10); //对账日期
          obj4.contractNo = row[i].contractNo; //合同编号
          obj4.initCharge = row[i].initCharge; //期初
          obj4.handleCharge = row[i].handleCharge; //应付
          obj4.alreadyCharge = row[i].alreadyCharge; //已付
          obj4.reconcyAmount = row[i].amount; //余额
          obj4.telType = 1; //文件类型
          obj4.accountNo = row[i].accountNo; //会计单号
          obj4.beginDate = obj4.abortDate.substr(0, 8) + "01"; //开始日期
          obj4.endDate = obj4.abortDate; //截止日期
          obj4.userId = constant.userId; // 用户id
          obj4.userName = constant.userName; // 用户名
          _Api.uploadSignFile(obj4).then(function(response) {
            var data_upload = response.data;
            if (data_upload.code == 1) {
              if (data_upload.total > 0) {
                //发起签署
                //参数
                var myDate = new Date();
                myDate.setMonth(myDate.getMonth() + 1);
                var obj3 = {
                  token: "",
                  project: "SRM",
                  create_by: this.$global.user.id, //签署文件发起人
                  doc: {
                    doc_no: row[i].accountNo, //签署文件编号-会计对账单号
                    send_id: "f2d9fe5e-e71d-4d10-a04f-41d950aa8d49", //签署发起人Id
                    title: data_upload.rows[0].orgName, //签署标题说明
                    doc_path: data_upload.rows[0].fileName, //签署文档路径
                    expire_date: myDate.toLocaleDateString(), //签署过期日期
                    business_templet_id: "", //行业类型id
                    scene_templet_id: "", //...
                    segment_templet_id: "", //证据点id
                    in_order: 0, //是否按顺序签署 0-否 1-是
                    remarks: "文件签署-测试", //备注
                  },
                  signerList: [
                    {
                      signer_id: "", //电子签帐号-公司
                      position_type: 0, //定位类型 0-坐标定位 1-关键字定位
                      sign_type: 0, //签署类型 0-单页Single 1 -多页Multi
                      pos_x: 460.34375, //签署横坐标
                      pos_y: 470.010416666667, //签署纵坐标
                      segment_prop_id1: "060112A6-2AD6-42B2-86EE-2EBF92658472", //签署方描述id(供应商编码)// supplier[0].supplierCode
                      segment_prop_id2: "11E86175-B6D5-4679-8109-D8B776D54C46", //签署方名称描述id(供应商名称)//supplier[0].supplierName
                      sort: 0, //按顺序签署时
                    },
                    {
                      signer_id: "", //电子签帐号-供应商
                      position_type: 0, //定位类型 0-坐标定位 1-关键字定位
                      sign_type: 0, //签署类型 0-单页Single 1 -多页Multi
                      pos_x: 96.34375, //签署横坐标
                      pos_y: 174.010416666667, //签署纵坐标
                      segment_prop_id1: "33AC7A74-D444-48E4-AA65-0695BC69F3AF", //签署方描述id(供应商编码)// supplier[0].supplierCode
                      segment_prop_id2: "42E50960-E17F-4214-8073-65761277DEAB", //签署方名称描述id(供应商名称)// supplier[0].supplierName
                      sort: 1, //按顺序签署时
                    },
                  ],
                };
                if (constant.appenv == "app") {
                  //正式环境
                  obj3.doc.business_templet_id =
                    "3957bfbd-7815-48b5-bf2e-95be92d19e27";
                  obj3.doc.scene_templet_id =
                    "b1dd60f7-54e2-4ea2-8f27-614c77372d9e";
                  obj3.doc.segment_templet_id =
                    "d3687f4c-b511-435f-a8e9-be172928c50d";

                  obj3.signerList[0].signer_id = row[i].ceSignAccount;
                  obj3.signerList[1].signer_id = row[i].seSignAccount;
                } else if (constant.appenv == "qas") {
                  //测试环境
                  obj3.doc.business_templet_id =
                    "1faf4a70-6011-4b3c-8a5b-c6a096477f61";
                  obj3.doc.scene_templet_id =
                    "caa4f4f3-095a-4719-bcc8-fcca0179e478";
                  obj3.doc.segment_templet_id =
                    "12972e15-dec2-4c01-8027-a6b6872be437";

                  obj3.signerList[0].signer_id = row[i].ceSignAccount;
                  obj3.signerList[1].signer_id = row[i].seSignAccount;
                } else {
                  //开发环境
                  obj3.doc.business_templet_id =
                    "1faf4a70-6011-4b3c-8a5b-c6a096477f61";
                  obj3.doc.scene_templet_id =
                    "caa4f4f3-095a-4719-bcc8-fcca0179e478";
                  obj3.doc.segment_templet_id =
                    "12972e15-dec2-4c01-8027-a6b6872be437";

                  obj3.signerList[0].signer_id = "yuanfeng";
                  obj3.signerList[1].signer_id = "lanshan";
                }
                //接口
                _Api.BeSign(obj3).then(function(response) {
                  var data_sign = response.data;
                  if (data_sign.Code == 0) {
                    //发起签署成功
                    var obj = {};
                    obj.flag = 3;
                    obj.id = row[i].id;
                    obj.accountNo = row[i].accountNo;
                    obj.callflag = 2;
                    obj.auditor = this.$global.user.employeeName;
                    obj.auditorId = this.$global.user.id;
                    _Api.putAccountBill(obj).then(function(response) {
                      let data = response.data;
                      if (data.code == "1") {
                        //移除审批完成的行
                        var a = [];
                        a.push(row[i]);
                        that.$refs.agGridComponent.gridOptions.api.updateRowData(
                          {
                            remove: a,
                          }
                        );
                      } else {
                        Msg.showErrorMsg(data.info);
                        return;
                      }
                    });
                    //
                  } else {
                    // that.$alert(data_sign.Error, {
                    //     showClose: false,
                    //     confirmButton: "确定",
                    //     customClass: "alertFailure"
                    // });
                    Msg.showErrorMsg(data_sign.Error);
                    return;
                  }
                }); //发起签署
              }
            } //上传文件的成功
            else {
              that.$alert(data_upload.info, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
              Msg.showErrorMsg(data_upload.info);
            }
          }); //上传文件的接口
        } //循环勾选的会计对账单
        //	            		this.$message({
        //							message: "操作成功",
        //							type: "success"
        //						});
        //						this.accountGridOptions.api.updateRowData({
        //							remove: row
        //						});
      }); //
    },
    abandonSelectedRows() {
      var row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要弃审的数据");
        return;
      }
    },
  },
  mounted() {
    var userTypeId = this.$global.user.userTypeId;
    if (userTypeId) {
      if (userTypeId == 4) {
        //供应商
        this.columnDefs.splice(2, 1); //不显示供应商列 jjc
        //					this.headerName = "客户";
      } else {
        //					this.headerName = "公司";
        //this.columnDefs.splice(1,1); //不显示公司列
        //this.columnDefs.splice(2,1);
      }
    }
  },
};

Date.prototype.Format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

function singleClickEditRenderer() {}
singleClickEditRenderer.prototype.init = function(params) {
  var template =
    '<span><button id="theValue" class="rendererClass">' +
    params.value +
    "</button></span>";
  var tempDiv = document.createElement("div");
  tempDiv.innerHTML = template;
  this.eGui = tempDiv.firstElementChild;

  this.params = params;
  this.eValue = this.eGui.querySelector("#theValue");
  this.eValue.innerHTML = params.value;
  // this.eButton = this.eGui.querySelector("#theButton");
  this.buttonClickListener = this.onButtonClicked.bind(this);
  this.eValue.addEventListener("click", this.buttonClickListener);
};

singleClickEditRenderer.prototype.onButtonClicked = function(event) {
  //	var value =this.params.value;
  accAuditApp2.__vue__.setClickValue(this.params.data);
};

singleClickEditRenderer.prototype.createGui = function() {};

singleClickEditRenderer.prototype.getGui = function() {
  return this.eGui;
};

singleClickEditRenderer.prototype.afterGuiAttached = function() {};

singleClickEditRenderer.prototype.destroy = function() {};

singleClickEditRenderer.prototype.isPopup = function() {
  return false;
};
</script>
